import { useAppStore } from "@/store";
import * as XLSX from "xlsx";
import moment from "moment";

// 设置主题色
export const changeThemeColor = (color) => {
  const appStore = useAppStore();
  appStore.setThemeColor(color);
  document.body.style.setProperty("--default", color);
  document.documentElement.style.setProperty("--el-color-primary", color);
};

/* 
  导出excel

  thead: 表头数据
   [{
    props: 'age',
    name: '年龄'
   }]

   data：表数据
   [{
    name: 'xiaoming',
    age: 12
   }]

   fileName: 文件名
   
   '人员统计'

   colWidths: 列宽
   [{
    wch: 20
   }]
*/
export const exportExcel = (thead, data, fileName, colWidths) => {
  const header = thead.map((item) => item.name);
  const sheetData = data.map((item) => {
    const row_obj = {};
    thead.forEach((th) => {
      row_obj[th.props] = item[th.props];
    });
    return row_obj;
  });
  const worksheet = XLSX.utils.json_to_sheet(sheetData);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet);
  XLSX.utils.sheet_add_aoa(worksheet, [header], { origin: "A1" });
  worksheet["!cols"] = colWidths;
  XLSX.writeFile(workbook, `${fileName}.xlsx`, { compression: true });
};

// 将时间段转换为每15分钟的时间对象
/**
 * 转换后的时间对象格式为
 * { t0000: '00:00', t0015: '00:15', ... }
 */
export const generateTimeObject = (timeStart, timeEnd) => {
  let startTime = moment(timeStart, "HH:mm");
  let endTime = moment(timeEnd, "HH:mm");
  let timeObject = {};

  while (startTime <= endTime) {
    let formattedTime = startTime.format("HH:mm");
    let key = `t${formattedTime.replace(":", "")}`;
    timeObject[key] = formattedTime;
    if (key == "t0000") {
      delete timeObject[key];
      key = "t2400";
      timeObject[key] = "24:00";
    }
    startTime = startTime.add(15, "minutes");
  }
  return timeObject;
};
